package com.gy.zpchat.ui.chat.group;

import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import im.zego.zim.ZIM;
import im.zego.zim.callback.ZIMGroupMemberListQueriedCallback;
import im.zego.zim.entity.ZIMCommandMessage;
import im.zego.zim.entity.ZIMCustomMessage;
import im.zego.zim.entity.ZIMError;
import im.zego.zim.entity.ZIMGroupMemberInfo;
import im.zego.zim.entity.ZIMGroupMemberQueryConfig;
import im.zego.zim.entity.ZIMGroupOperatedInfo;
import im.zego.zim.entity.ZIMMessage;
import im.zego.zim.entity.ZIMMessageReceiptInfo;
import im.zego.zim.entity.ZIMTextMessage;
import im.zego.zim.enums.ZIMConversationType;
import im.zego.zim.enums.ZIMErrorCode;
import im.zego.zim.enums.ZIMMessageDirection;
import im.zego.zim.enums.ZIMMessageReceiptStatus;
import im.zego.zim.enums.ZIMMessageType;
import com.gy.zpchat.MyApplication;
import com.gy.zpchat.R;
import com.gy.zpchat.SDKManager;
import com.gy.zpchat.entity.MessageInfo;
import com.gy.zpchat.enums.ChatItemType;
import com.gy.zpchat.ui.chat.base.ZIMChatBaseActivity;

public class ZIMGroupChatActivity extends ZIMChatBaseActivity implements SDKManager.OnReceiveGroupMessage{

    public static void actionStart(Activity activity, String groupID, String groupName,String draft) {
        Intent intent = new Intent(activity, ZIMGroupChatActivity.class);
        intent.putExtra("conversationID", groupID);
        intent.putExtra("conversationName", groupName);
        intent.putExtra("draft", draft);
        activity.startActivity(intent);
    }

    private static final String TAG = "ZIMGroupChatActivity";
    private static final int QUERY_GROUP_MESSAGE_COUNT = 30;

    private static final int QUERY_GROUP_MEMBER_COUNT = 500;
    private ArrayList<ZIMGroupMemberInfo> groupMemberList = new ArrayList<>();
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.group_detail, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override

    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                this.finish();
                break;
            case R.id.group_detail:
                Intent intent = new Intent(this, ZIMGroupInfoDetailActivity.class);
                intent.putExtra("groupID", conversationID);
                detailActivityResultLauncher.launch(intent);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.zimConversationType = ZIMConversationType.GROUP;
        setMessageTitle(conversationName);


        queryGroupMemberInfo(0);
        SDKManager.sharedInstance().addGroupNameUpdateCallback(groupNameUpdateCallback);
        SDKManager.sharedInstance().clearConversationUnreadMessageCount(conversationID, ZIMConversationType.GROUP);
        SDKManager.sharedInstance().addReceiveGroupMessageCallback(this);
        SDKManager.sharedInstance().queryGroupMessage(conversationID, null, QUERY_GROUP_MESSAGE_COUNT, true, this);
        SDKManager.sharedInstance().setMessageReceiptChangedCallback(new SDKManager.OnMessageReceiptChangedCallback() {
            @Override
            public void onMessageReceiptChanged(ZIM zim, ArrayList<ZIMMessageReceiptInfo> infos) {
                for (ZIMMessageReceiptInfo info : infos) {
                    List<MessageInfo> messageInfoList = chatContentAdapter.getMessageInfoList();
                    for (int i = 0; i < messageInfoList.size(); i++) {
                        if (messageInfoList.get(i).getZIMMessage().getMessageID() == info.messageID){
                            messageInfoList.get(i).setZimMessageReceiptStatus(info.status);
                            messageInfoList.get(i).setReceiptUnreadMemberCount(info.unreadMemberCount);
                            chatContentAdapter.notifyItemChanged(i);
                            break;
                        }
                    }
                }
            }
        });
        findViewById(R.id.setting_icon).setVisibility(View.VISIBLE);
    }

    private void queryGroupMemberInfo(int nextFlag) {
        ZIMGroupMemberQueryConfig config = new ZIMGroupMemberQueryConfig();
        config.count = QUERY_GROUP_MEMBER_COUNT;
        config.nextFlag = nextFlag;
        SDKManager.sharedInstance().queryGroupMemberList(conversationID, config, new ZIMGroupMemberListQueriedCallback() {
            @Override
            public void onGroupMemberListQueried(String groupID, ArrayList<ZIMGroupMemberInfo> userList, int nextFlag, ZIMError errorInfo) {
                if (errorInfo.code == ZIMErrorCode.SUCCESS){
                    groupMemberList.addAll(userList);
                    if (nextFlag!=0){
                        queryGroupMemberInfo(nextFlag);
                    }else {
                        HashMap<String ,String> map = new HashMap<>();
                        for (ZIMGroupMemberInfo zimGroupMemberInfo : groupMemberList) {
                            map.put(zimGroupMemberInfo.userID,zimGroupMemberInfo.memberAvatarUrl);
                        }
                        if (!map.isEmpty()){
                            chatContentAdapter.setAvatarMap(map);
                            chatContentAdapter.notifyItemRangeChanged(0,chatContentAdapter.getItemCount());
                        }
                    }
                }
            }
        });
    }

    public void setting(View view) {
        Intent intent = new Intent(this, ZIMGroupInfoDetailActivity.class);
        intent.putExtra("groupID", conversationID);
        detailActivityResultLauncher.launch(intent);
    }

    private SDKManager.OnGroupNameUpdateCallback groupNameUpdateCallback =
        new SDKManager.OnGroupNameUpdateCallback() {
            @Override
            public void onGroupNameUpdated(ZIM zim, String groupName,
                                           ZIMGroupOperatedInfo operatedInfo, String groupID) {
                setMessageTitle(groupName);
            }
        };

    public void setMessageTitle(String name) {
        String groupName = name;
        if (groupName != null && !"".equals(groupName)) {
            setTitle(groupName);
        } else {
            setTitle(conversationID);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void sendMsg(String content) {
        if ("".equals(content.replace(" ", ""))) {
            Toast.makeText(ZIMGroupChatActivity.this, "Please enter valid content", Toast.LENGTH_LONG).show();
            return;
        }

        CheckBox cbCommand = findViewById(R.id.isCommand);
        CheckBox cbCustom = findViewById(R.id.isCustom);
        ZIMMessage zimMessage;
        String pushContent = "";
        if (cbCommand.isChecked()) {
            ZIMCommandMessage commandMessage = new ZIMCommandMessage();
            commandMessage.message = content.getBytes(StandardCharsets.UTF_8);

            zimMessage = commandMessage;
        }else if (cbCustom.isChecked()){
            ZIMCustomMessage customMessage = new ZIMCustomMessage(content, 100);
            customMessage.searchedContent="searchContent";
            zimMessage = customMessage;
        } else {
            ZIMTextMessage zimTextMessage = new ZIMTextMessage();
            zimTextMessage.message = content;
            zimMessage = zimTextMessage;
            pushContent = content;
        }

        setMessageMention(zimMessage);
        SDKManager.sharedInstance().sendGroupMessage(zimMessage, conversationID, getSendConfig(conversationID,pushContent), this);
    }

    @Override
    protected void onLoadMsg() {
        MessageInfo info = chatContentAdapter.getMessage(0);
        if (info != null) {
            SDKManager.sharedInstance().queryGroupMessage(conversationID, info.getZIMMessage(), QUERY_GROUP_MESSAGE_COUNT, true, this);
        }
    }

    ActivityResultLauncher<Intent> detailActivityResultLauncher = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == ZIMGroupInfoDetailActivity.DELETE_MEMBER_RESULT_CODE) {
                        // There are no request codes
                        Intent data = result.getData();
                        boolean isClear = data.getBooleanExtra("clear_message", false);
                        if (isClear) {
                            clearAllMsg();
                        }
                    }else if (result.getResultCode() == ZIMGroupMemberSelectActivity.SELECT_MEMBER_RESULT_CODE){
                        Intent data = result.getData();
                        if (data!=null){
                            Bundle bundle = data.getBundleExtra("select member");
                            ArrayList<String> selectMembers = bundle.getStringArrayList("members");
                            if (selectMembers!=null && !selectMembers.isEmpty()){
                                callInvite(selectMembers);
                            }
                        }
                    }
                }
            });

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SDKManager.sharedInstance().removeGroupNameUpdateCallback(groupNameUpdateCallback);
        SDKManager.sharedInstance().removeReceiveGroupMessageCallback(this);

    }

    @Override
    protected void onClickCallAction() {
        // 选择多人
        Intent intent = new Intent(this, ZIMGroupMemberSelectActivity.class);
        intent.putExtra("groupID", conversationID);
        intent.putExtra("unSelectMemberUid", MyApplication.sUserId);
        detailActivityResultLauncher.launch(intent);
    }

    @Override
    public void onReceiveGroupMessage(ZIM zim, ArrayList<ZIMMessage> messageList, String fromGroupID) {
        ArrayList<ZIMMessage> receiptMessageList = new ArrayList<>();
        for (ZIMMessage message : messageList) {
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_LEFT);
            messageInfo.setZIMMessage(message);
            addMsg(messageInfo);
            if (message.getReceiptStatus()!=ZIMMessageReceiptStatus.NONE){
                receiptMessageList.add(message);
            }
        }
        if (!receiptMessageList.isEmpty()){
            sendMessageReceiptsRead(receiptMessageList);
        }
        SDKManager.sharedInstance().clearConversationUnreadMessageCount(conversationID, ZIMConversationType.GROUP);
    }

    @Override
    public void onMessageQueried(String conversationID, ZIMConversationType conversationType, ArrayList<ZIMMessage> arrayList, ZIMError zimError) {
        super.onMessageQueried(conversationID, conversationType, arrayList, zimError);
        Collections.reverse(arrayList);
        List<ZIMMessage> needQueryReceiptMessageList = new ArrayList<>();
        List<ZIMMessage> sendReceiptMessageList = new ArrayList<>();//需要去已读的消息列表，这里默认所有非自己发的消息查出来后都要去已读.
        for (ZIMMessage message : arrayList) {
            MessageInfo messageInfo = new MessageInfo();
            if (message.getType() == ZIMMessageType.SYSTEM||message.getType() == ZIMMessageType.REVOKE){
                messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_CENTER);
            }else if (message.getSenderUserID().equals(SDKManager.sharedInstance().zimUserInfo.userID)) {
                messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_RIGHT);
            } else {
                messageInfo.setType(ChatItemType.CHAT_ITEM_TYPE_LEFT);
            }
            messageInfo.setZIMMessage(message);
            if (message.getReceiptStatus() != ZIMMessageReceiptStatus.NONE && message.getReceiptStatus()!=ZIMMessageReceiptStatus.DONE){
                needQueryReceiptMessageList.add(message);
                if (message.getDirection() == ZIMMessageDirection.RECEIVE){
                    sendReceiptMessageList.add(message);
                }
            }
            addMsgToTop(messageInfo);
        }
        if (!needQueryReceiptMessageList.isEmpty()){
            queryMessageReceipt(needQueryReceiptMessageList);
        }

        if (!sendReceiptMessageList.isEmpty()){
            sendMessageReceiptsRead(sendReceiptMessageList);
        }
    }

}
